<?php
if( !defined( 'EMAIL' ) ): define( 'EMAIL', 1 );
if( !defined( 'FILE_ROOT' ) ) include_once( '../../_prerun' );

/**
 * GESTION D'ENVOIS D'EMAILS
 */
require_once( OTHERLIB_ROOT . 'phpmailer/class.phpmailer.php' );
USE_LIB( 'template' );
USE_APP( 'variable' );
USE_APP( 'params' );

class Email extends Template
	{
	protected $m_get_subject = false;
	protected $phpemail = null;

	/**
	 *
	 */
	public function __construct( $tpl_filename = '' )
		{
		parent::__construct( $tpl_filename );
		$this->phpemail = new PHPMailer();
		$this->phpemail->From = SITE_FROM;
		$this->phpemail->FromName = SITE_FROM_NAME;
		$this->phpemail->IsHTML( true );
   	$this->m_get_subject = false;
		}

	public function __destruct()
		{
		unset($this->phpemail);
		}

	public function __call( $method, $args )
		{
		if(method_exists($this->phpemail,$method))
			{
			return call_user_func_array(array($this->phpemail,$method),$args);
			}
		else
		if(!method_exists($this,$method) && method_exists($this->phpemail,$method) && isset($args[0]))
			{
			return $this->phpemail->{$method} = $args[0];
			}
		}

	public function __get( $varname )
		{
		if( !isset( $this->{$varname} ) && isset( $this->phpemail->{$varname} ) )
			{
			return $this->phpemail->{$varname};
			}
		}

	public function __set( $varname, $varvalue )
		{
		if( isset( $this->phpemail->{$varname} ) )
			return $this->phpemail->{$varname} = $varvalue;
		}
		
	public function __clone()
		{
		$this->phpemail = new phpmailer();
		}


   /**
    * est-ce que l'adresse est un email ?
    * @param string $email
    * @param bool $security # doit-t-on filtrer le spamming ?
    * @return bool
    */
   static function isEmail( $email, $security = true )
      {
      if( $security && strpos( $email, SITE_NAME ) > 0 )
      	{
         return false;
      	}
      else
      	{
			$phpemail = new phpmailer();
         return $phpemail->IsEmail( $email );
      	}
      }


   /**
    * supprime les adresses de destination
    */
   public function resetTo()
      {
      $this->phpemail->to = array();
      }


   /**
    * ajoute des destinataires
    * @param array $a
    */
   public function addArrayAddress( $array )
      {
		if( is_string( $array ) && stripos($array, ';' )!==false )
			{
			$array = explode( ';', $array );
			foreach( $array as $a )
				$this->phpemail->AddAddress( $a );
			}
		else
		if( is_string( $array ) )
			{
			$this->phpemail->AddAddress( $array );
			}
		else
			{
			foreach( $array as $a )
				$this->phpemail->AddAddress( $a );
			}
      }


   /**
    * ajoute des destinataires BCC
    * @param array $a
    */
   public function addArrayAddressBCC( $array )
      {
		if( is_string( $array ) && stripos($array, ';' )!==false )
			{
			$array = explode( ';', $array );
			foreach( $array as $a )
				$this->phpemail->AddBCC( $a );
			}
		else
		if( is_string( $array ) )
			{
			$this->phpemail->AddBCC( $array );
			}
		else
			{
			foreach( $array as $a )
				$this->phpemail->AddBCC( $a );
			}
      }


   /**
    * envois le mail aux destinataires
    * @param bool $raw # doit-on l'envoyer en texte ?
    * @return bool
    */
   function send( $dest = null, $inline = false, $alt = false )
      {
      if( isset( $dest ) )
      	{
	      if( strpos( $dest, ';' ) > 0 )
	      	$dest = explode( ';', $dest );
	      if( is_array( $dest ) )
	      	{
	      	foreach( $dest as $address )
	      		{
	      		$address = trim( $address );
	      		if( $this->isEmail( $address ) )
						$this->phpemail->AddAddress( $address );
	      		}
	      	}
	      else
	      	$this->phpemail->AddAddress( $dest );
      	}
      else
      	$dest = SITE_TO;

      $this->phpemail->IsHTML(true);

		$this->parseIncludeFile();
		$this->parseUsersVariables();
		$this->parseVarDefinition();
		$this->parseCommons();
		$this->parseFunction();
		$this->parseCondition();

      $h = $this->getHTML();
      $this->phpemail->Body = $this->phpemail->FixEOL($h);
      $this->phpemail->AltBody = strip_tags($this->phpemail->Body);

      if( $this->m_get_subject || empty( $this->phpemail->Subject ) )
      	{
	      if(preg_match('|<title>([^<]+)</title>|', $h, $founds))
	      	{
		      if(isset($founds[1]))
	      		$this->phpemail->Subject = $founds[1];
	      	}
	      }

      if( $inline )
			$this->processInlineImage();

		if( $alt )
			{
	      $this->phpemail->AltBody = $this->getAlternativeContent($content);
			}

		if( DEBUG_EMAILS == 1 )
			{
			$dir_name = FILE_ROOT . '_emails_debug';
			if( !(file_exists( $dir_name ) && is_dir( $dir_name ) ) )
				{
				mkdir( $dir_name, 01777 );
				}
			$filename = $dir_name . '/' . filename( $this->phpemail->Subject );
			file_put_contents( $filename, $this->phpemail->Body );
			$ret = true;
			}
		else
	      $ret = $this->phpemail->Send();

      $this->phpemail->ClearAddresses();

      return( $ret );
      }


   /**
    * envois le mail a SITE_TO
    * @param bool $raw # doit-on l'envoyer en texte ?
    * @return bool
    */
   public function sendToMe( $raw = false )
   	{
   	$this->send();
   	}
   	
	public function getAlternativeContent( $content )
		{
      $content = str_replace('<br />',"\r\n",$content);
		$content = preg_replace("/<title>(.*)<\/title>/", "",$content);
      $blocks = array('h1');
      foreach($blocks as $block)
      	{
			$content = preg_replace("/<".$block.">(.*)<\/".$block.">/", "\r\n** \\1 **\r\n",$content);
      	}
      $blocks = array('strong','em');
      foreach($blocks as $block)
      	{
			$content = preg_replace("/<".$block.">(.*)<\/".$block.">/", "* \\1 *",$content);
      	}
      $blocks = array('p','div', 'ul', 'li');
      foreach($blocks as $block)
      	{
			$content = preg_replace("/<".$block.">(.*)<\/".$block.">/", "\r\n\\1\r\n",$content);
      	}
		$content = preg_replace("/<a(.*)? href=\"(.*)\"(.*)?>(.*)<\/a>/", "\\4 (\\2)",$content);
		$content = preg_replace('/<img(.*)?src="([^"]+)"(.*)?alt="([^"]+)"(.*)?\/?>/', "image : \\2 (\\4)",$content);
		$content = preg_replace('/<img(.*)?alt="([^"]+)"(.*)?src="([^"]+)"(.*)?\/?>/', "image : \\4 (\\2)",$content);
		
		return stripslashes( $content );
      }

   public function processInlineImage()
   	{
   	$content = $this->phpemail->Body;
   	$img_content = str_replace( '><img', ">\n<img", strip_tags( $content, '<img>' ) );
   	$id = 0;
   	$replacement_done = array();
		if( preg_match_all( '/<img(.*)src="([^"]+)"([^>]+)?>/', $img_content, $matches ) && isset( $matches[1] ) )
			{
			for( $id=0, $max = count( $matches[1] ); $id < $max; $id++ )
				{
				$tag = $matches[0][ $id ];
				$path = $matches[2][ $id ];
   			$path = str_ireplace( WWW_ROOT, '', $path );
				if( $this->imageIsInline( $path ) )
					{
					# 0 contient le tag img
					# 1 contient le chemin de l'image
					$cid = $id . '@' . $this->getInlineImageName( $path );
			   	$this->AddEmbeddedImage(
			   		FILE_ROOT . $path,
			   		$cid,
			   		$this->getInlineImageName( $path ),
			   		$encoding = "base64",
			   		$type = $this->getInlineImageMime( $path )#"image/jpeg"
			   		);
			   	$new_tag = str_replace( $path, 'cid:' . $cid, $tag );
			   	$content = str_replace( $tag, $new_tag, $content );
					}
				}
			}
		$this->phpemail->Body = $content;
   	}
   	
   public function imageIsInline( $path )
   	{
   	if( strpos( $path, ':' ) === false )
   		{
   		$infos = pathinfo( FILE_ROOT . $path );
   		if( file_exists( FILE_ROOT . $path ) )
   			{
   			$name = isset( $infos['filename'] ) ? $infos['filename'] : $infos['basename'];
   			return( eregi( '^i_(.*)$', $name ) );
   			}
   		}
   	return false;
   	}
   	
   public function getInlineImageName( $path )
   	{
   	$infos = pathinfo( FILE_ROOT . $path );
		return preg_replace( '/i_(.*)/', '\\1', $infos['basename'] );
   	}
   	
   public function getInlineImageMime( $path )
   	{
   	$infos = getimagesize( FILE_ROOT . $path );
   	if( isset( $infos['mime'] ) )
   		return $infos['mime'];
   	else
   		return 'image/png';
   	}
	}
endif;
?>